package com.mayflygeek.mayflyask.framework.orm.entity;

import java.util.List;

import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

import com.google.common.collect.Lists;

/**
 * @author 虫虫
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * @Emial chongchong@mayflygeek.com
 * 
 */
@MappedSuperclass
public class TreeEntity<E extends TreeEntity<E>> extends NameEntity implements ITreeEntity<E> {
	private static final long serialVersionUID = -972944756206337337L;

	/**
	 * 父级
	 */
	@ManyToOne
	@JoinColumn(name = "parent_id")
	protected E parent;
	
	/**
	 * 包含子集
	 */
	@OneToMany(mappedBy = "parent")
	@Cascade(CascadeType.ALL)
	private List<E> children = Lists.newArrayList();
	
	public TreeEntity() {
		
	}
	
	public TreeEntity(String name) {
		super(name);
	}
	
	@Override
	public boolean isRoot() {
		return this.getParent() == null;
	}

	@Override
	public boolean isLeaf() {
		return children.isEmpty();
	}

	@SuppressWarnings("unchecked")
	@Override
	public E addChild(E... entities) {
		for(E e : entities) {
			e.setParent((E)this);
			getChildren().add(e);
		}
		return (E) this;
	}

	@Override
	public E getParent() {
		return parent;
	}

	@Override
	public void setParent(E parent) {
		this.parent = parent;
	}

	@Override
	public List<E> getChildren() {
		return children;
	}

	@Override
	public void setChildren(List<E> children) {
		this.children = children;
	}

}
